package com.itheima.security.distributed.order.common;

import com.itheima.security.distributed.order.model.UserDto;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author: yangguoxiong
 * @date: 2022/3/8 16:08
 * @description:
 */
public class JwtUtil {

    public static String BEARER = "bearer";
    public static Integer AUTH_LENGTH = 7;
    public static String SIGNING_KEY = "uaa123";

    public static String getToken(String auth) {
        if (auth != null && auth.length() > AUTH_LENGTH) {
            String headStr = auth.substring(0, 6).toLowerCase();
            if (headStr.compareTo(BEARER) == 0) {
                auth = auth.substring(7);
            }
            return auth;
        } else {
            return null;
        }
    }

    public static Claims parseJWT(String jsonWebToken) {
        try {
            return (Claims) Jwts.parser().setSigningKey(Base64.getDecoder().decode(getBase64Security())).parseClaimsJws(jsonWebToken).getBody();
        } catch (Exception var2) {
            return null;
        }
    }

    public static String getBase64Security() {
        return Base64.getEncoder().encodeToString(SIGNING_KEY.getBytes(StandardCharsets.UTF_8));
    }

    public static UserDto getUser() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        UserDto user = (UserDto) request.getAttribute("USER_REQUEST_ATTR");
        if (user == null) {
            String auth = request.getHeader("Authorization");
            Claims claims = null;
            String token = "";
            if (StringUtils.isNotBlank(auth)) {
                token = getToken(auth);
            }
            if (StringUtils.isNotBlank(token)) {
                claims = parseJWT(token);
            }
            if (claims == null) {
                return null;
            }

            String userId = String.valueOf(claims.get("userId"));
            String username = String.valueOf(claims.get("username"));
            String roleName = String.valueOf(claims.get("roleName"));
            user = new UserDto();
            user.setId(userId);
            user.setUsername(username);
            user.setRoleName(roleName);

            request.setAttribute("USER_REQUEST_ATTR", user);
        }
        return user;
    }

    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : ((ServletRequestAttributes)requestAttributes).getRequest();
    }

}
